package com.hongyuan.sellfitness.ui.main.view_mode;

import android.app.Application;
import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import com.hongyuan.mvvmhabitx.bus.RxBus;
import com.hongyuan.mvvmhabitx.bus.RxSubscriptions;
import com.hongyuan.mvvmhabitx.bus.event.SingleLiveEvent;
import com.hongyuan.sellfitness.base.Constants;
import com.hongyuan.sellfitness.base.CustomViewModel;
import com.hongyuan.sellfitness.data.MyRepository;
import com.hongyuan.sellfitness.pushservice.MssagePosition;
import com.hongyuan.sellfitness.ui.main.beans.CheckVersionBeans;
import com.hongyuan.sellfitness.ui.main.beans.MessageNumBeans;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class MainViewModel extends CustomViewModel<MyRepository> {

    private Disposable mSubscription;

    public ObservableField<CheckVersionBeans.InfoBean> entity = new ObservableField<>();

    public MainViewModel(@NonNull Application application, MyRepository model) {
        super(application, model);
    }

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        //显示进出店二维码
        public SingleLiveEvent<Void> showMessagePage = new SingleLiveEvent<>();
        //设置消息数量
        public SingleLiveEvent<Integer> setMessageNum = new SingleLiveEvent<>();
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mSubscription = RxBus.getDefault().toObservable(MssagePosition.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(progressLoadBean -> {
                    //显示消息页面
                    uc.showMessagePage.call();
                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        //取消订阅，防止内存泄漏
        RxSubscriptions.remove(mSubscription);
    }

    @Override
    protected void returnData(int code, Object dataBean) {
        super.returnData(code, dataBean);

        if(code == Constants.CHECK_APP_VERSION){
            CheckVersionBeans.InfoBean bean = ((CheckVersionBeans)dataBean).getInfo();
            entity.set(bean);
        }

        if(code == Constants.GET_MSG_UNREAD_INFO){
            MessageNumBeans numBeans = (MessageNumBeans)dataBean;

            uc.setMessageNum.setValue(numBeans.getAll());
        }
    }
}
